<?php
/**
 * 基础控制器
 *
 * @author Fong.zhang
 */
namespace Home\Controller;

use Think\Controller;

class BaseController extends Controller
{
    /**
     * 返回数组
     * @var array
     */
    private $_data = array(
        'error' => null,
        'data' => null
    );

    /**
     * 初始化
     */
    public function _initialize () {
        $this->_checkLogin();

        //生成语言包
        $this->_generateJsLanguageFile();

        $this->assign(array(
            'URL_PATH' => strtolower(CONTROLLER_NAME . '/' . ACTION_NAME)
        ));
    }

    /**
     * Ajax返回
     * @param array $data
     */
    public function ajaxReturn ($data = array()) {
        $this->_data = array_merge($this->_data, $data);

        return parent::ajaxReturn($this->_data);
    }

    /**
     * 根据当前语言设置生成语言包
     * @return void
     */
    private function _generateJsLanguageFile () {
        if (C("LANG_SWITCH_ON")) {
            $jsLangFilePath = "./Public/js/lang";
            $langList = L();
            $jsLangFileName = $jsLangFilePath . "/" . LANG_SET . ".js";
            //@unlink($jsLangFileName);//测试，不永久缓存语言包
            //已存在语言包
            if (is_file($jsLangFileName)) {
                return;
            }
            $str = "var \$LANG={";
            $total = count($langList);
            $k = 1;
            foreach ($langList as $key => $value) {
                $str .= $key . ":'" . $value . "'";
                if ($k < $total) {
                    $str .= ",";
                }
                // $str .="\r\n";
                $k++;
            }
            if (!empty($str)) {
                $str .= "}";
                $file_handel = fopen($jsLangFileName, "w+");//打开文件，重写模式
                fwrite($file_handel, $str);
                fclose($file_handel);
            }
        }
    }

    /**
     * 检查是否登录
     * @return void
     */
    private function _checkLogin () {
        $sessionKey = session('sso_session_key');
        if (!$sessionKey) {
            $this->redirect('login/index');
        }
    }
}